//
//  YAStatusDAL.swift
//  KeepCliming
//
//  Created by 鱼龙之梦 on 15/9/18.
//  Copyright © 2015年 panyanzhi. All rights reserved.
//

import UIKit

private let clearCaheTimeTravel:NSTimeInterval = -60*60*24*5
class YAStatusDAL: NSObject {
     //MARK:--- 定期清理缓存 (放在代理类的程序到后台时调用)
    class func clearCacheStatus(){
        let date = NSDate(timeIntervalSinceNow: clearCaheTimeTravel)
        let df = NSDateFormatter()
        df.dateFormat = "yyyy-MM-dd HH:mm:ss"
        let str = df.stringFromDate(date)
        let sql = "DELETE FROM weibCache WHERE createTime < '\(str)'"
        SQLiteManager.sharedManager.execSQL(sql)
    }
    //将加载数据的代码方法在这里
    //MARK:---加载缓存，如果有就返回结果，没有则取网络里拿;将结果回调回来（返回字典数组）
    class func loadStatues(since_id:Int,max_id:Int,completion:(array:[[String:AnyObject]]?)->()) {
        let list = loadCacheSatatus(since_id, max_id: max_id)
        if list?.count ?? 0>0{
            completion(array: list)
            return
        }
        //执行到这里，说明没有缓存的数据
        YANetworking.sharedTools.loadStatus(since_id: since_id, max_id: max_id).subscribeNext({ (result) -> Void in
            guard let array = result["statuses"] as? [[String:AnyObject]] else{
               printLog("没有正确的数据")
               completion(array: nil)
               return
            }
            //printLog(array)
            saveStatus(array)
            completion(array: array)
          }, error: { (error) -> Void in
            completion(array: nil)
            }) { () -> Void in
                printLog("信号完成")
        }
    }
     //MARK:--- 从缓存里查询数据
    class func loadCacheSatatus(since_id:Int,max_id:Int)->[[String:AnyObject]]?{
        let UId = YAUserAcountVM.sharedUserAccount.userAcount!.uid!
        //查询指定用户的微博缓存数据
        var sql = "SELECT weiboData FROM weibCache WHERE UId = \(UId)\n"
        if since_id>0{
            sql += "AND weiboId > \(since_id)\n"
        } else if max_id > 0{
            sql += "AND weiboId < \(max_id)\n"
        }
        sql += "ORDER BY weiboId DESC LIMIT 20"
        //定义一个字典数据接收返回的查询的结果集
        var result:[[String:AnyObject]]?
        if let list = SQLiteManager.sharedManager.execRercordSet(sql){
            result = [[String:AnyObject]]()
            //将结果集序列化为json对象
            for item in list {
                let statusString = item["weiboData"] as! String
                let data = statusString.dataUsingEncoding(NSUTF8StringEncoding)!
                let dict = try!NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions(rawValue: 0)) as![String :AnyObject]
                result?.append(dict)
            }
        }
        return result
    }
     //MARK:--- 每次去请求网络数据都去调用这个方法保存缓存数据
    class func saveStatus(array:[[String:AnyObject]]){
        //批量数据 引入事务
        let manager = SQLiteManager.sharedManager
        manager.beginTranscation()
        let sql = "INSERT INTO weibCache (weiboId,weiboData,UId) VALUES (?,?,?);"
        let UId = YAUserAcountVM.sharedUserAccount.userAcount!.uid!
        //数据操作结果标记
        var result = true
        for dict in array{
            let weiboId = dict["id"] as! Int
            //将字典转换为字符串
            let data = try! NSJSONSerialization.dataWithJSONObject(dict, options: NSJSONWritingOptions(rawValue: 0))
            let statusString = String(data:data,encoding:NSUTF8StringEncoding)!
            result = manager.prepareExecSQL(sql, parmas:weiboId,statusString,UId)
            if !result {
                break
            }
        }
        if result{
            printLog("提交事务")
            manager.commitTranscation()
        }
        else {
            print("回滚事务")
            manager.rollBackTranscation()
        }
    }
}
